package com.example.myapplication.util

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.example.myapplication.BaseActivity
import com.example.myapplication.activity.HomeAty
import java.util.*

object ActivityStack {
    private val stack= Stack<Activity>()

    fun pushIn(aty:Activity){
        stack.push(aty)
    }

    fun popOut(aty:Activity,isRefresh: Boolean?=false){
        if (stack.contains(aty)){
            stack.remove(aty)
        }
        aty.finish()
        if (stack.isEmpty())return
        val a=  stack.peek()
        if (isRefresh==true){
            if (a is BaseActivity){
                //刷新
                a.refreshState(null);
            }
        }
    }

    fun <T> popUntil(className:Class<T>,isRefresh:Boolean?=false,bundle: Bundle?=null){
        val aty= stack.peek()
        if (aty.javaClass==className||aty is HomeAty){
            if (isRefresh==true){
                val baseActivity = aty as BaseActivity
                baseActivity.refreshState(bundle)
            }
        }else{
            stack.pop()
            aty.finish()
            popUntil(className,isRefresh,bundle)
        }
    }

    fun <T> startTo(c: Context, className:Class<T>, bundle: Bundle?=null){
        val intent= Intent(c,className)
        intent.flags= Intent.FLAG_ACTIVITY_CLEAR_TOP
        intent.putExtra("data",bundle)
        c.startActivity(intent)
    }
    fun <T> startTo(c: Activity, className:Class<T>, bundle: Bundle?=null){
        val intent= Intent(c,className)
        intent.flags= Intent.FLAG_ACTIVITY_CLEAR_TOP
        intent.putExtra("data",bundle)
        c.startActivity(intent)
    }

    fun <T,N> popUtilAndStart(c:Context, className1:Class<T>, className2:Class<N>){
        popUntil(className1)
        startTo(c,className2)
    }

}